import type { Directive } from 'vue'

const DURATION = 1500

export const increase: Directive = {
  mounted(el, binding) {
    const { value: maxCount } = binding

    el.$animate = animate((progress) => {
      el.innerText = Math.floor(progress * maxCount)
    }, DURATION)
  },
  unmounted(el) {
    el.$animate?.cancel()
  }
}
export function animate(
  callback: (progress: number) => void,
  duration: number
) {
  let animation: number, start: number, cancel: () => void
  const anim = () => {
    const now = new Date().getTime()
    const progress = Math.floor(((now - start) / duration) * 100) / 100
    callback(progress > 1 ? 1 : progress)
    if (now - start > duration) {
      cancel()
    }
    cancel = () => {
      cancelAnimationFrame(animation)
    }
    start = new Date().getTime()
    animation = requestAnimationFrame(anim)
    return {
      cancel: () => {
        cancelAnimationFrame(animation)
      }
    }
  }
  anim()
}
